/**
 * Created by Administrator on 2017/3/21.
 */
import React, { Component } from 'react';
import {Form, Input, DatePicker,Switch, Select, message, Button, Tooltip, Icon, Alert, TimePicker} from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import request from '@/utils/request';
import find from 'lodash/find';

const FormItem = Form.Item;
const Option = Select.Option;
let uuid = 10;

class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      meterArr: [1, 2, 3, 4, 5, 6, 7, 8,9,10],
      meterActiveKey: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
      meter1: [],
      meter2: [],
      meter3: [],
      meter4: [],
      meter5: [],
      meter6: [],
      meter7: [],
      meter8: [],
      meter9: [],
      meter10: [],
    };
  }

  clearTable = () => {
    uuid = 10;
    this.setState({
      meterArr: [1, 2, 3, 4, 5, 6, 7, 8,9,10],
      meterActiveKey: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
      meter1: [],
      meter2: [],
      meter3: [],
      meter4: [],
      meter5: [],
      meter6: [],
      meter7: [],
      meter8: [],
      meter9: [],
      meter10: [],
    });
    this.props.form.resetFields();
  };

  componentDidMount() {
    const that = this;
    // this.fetchMeter('meter1');
    // this.fetchMeter('meter2');
    // this.fetchMeter('meter3');
    let hours_of_day=(this.props.editRecord&&this.props.editRecord.hardware_configs.wh&&this.props.editRecord.hardware_configs.wh.upload_time)?
      this.props.editRecord.hardware_configs.wh.upload_time.hours_of_day:[];
    for(let i=0;i<hours_of_day.length;i++){
      that.props.form.setFieldsValue({
        [`useMantissa-${i+1}`]: hours_of_day[i].useMantissa,
        [`time-${i+1}`]: moment(`${hours_of_day[i].hour}:${hours_of_day[i].minute}`,'HH:mm'),
      });
    }
  }

  addMeter = () => {
    uuid++;
    this.state.meterArr.push(uuid);
    this.state.meterActiveKey.push(uuid.toString());
    this.setState({
      [`meter${uuid}`]: [],
      meterArr: this.state.meterArr,
      meterActiveKey: this.state.meterActiveKey,
    });
  };
  deleteMeter = (item) => {
    console.log('删除的item', item);
    if (this.state.meterArr.length === 1) {
      console.log('只有一个水表');
      // message.error('至少需要一个水表')
      // return false
    }
    const index = this.state.meterArr.indexOf(item);
    console.log('index', index);
    this.state.meterArr.splice(index, 1);
    this.setState({
      meterArr: this.state.meterArr,
    });
  };
  handleChange = (value, item,index) => {
    console.log(value);
    console.log(this.state[`meter${item}`]);
    // const address = find(this.state[`meter${item}`], o => o.number === value).address;
    const that = this;
    if(!value){
      message.error('请输入水表号');
      return false
    }
    const formValues = this.props.form.getFieldsValue();
    if(!formValues.company_id){
      message.error('请先选择公司')
      return  false
    }
    request(`/meters/${value}`, {
      method: 'GET',
      params:{
        company_id:formValues.company_id
      }
    }).then((response) => {
      if (response.status === 200) {
        that.props.form.setFieldsValue({
          [`meter_address-${item}`]: response.data.data.address,
          [`pre_meter_date-${item}`]: response.data.data.meter_data.upload_time.substr(0,10),
          [`pre_meter_value-${item}`]: response.data.data.meter_data.value,
        });
        if(document.querySelector(`.custom-table-form${index}`)){
           document.querySelector(`.custom-table-form${index} .meter_value input`).focus()
        }
      }
    });


  };

  render() {
    const formItemLayoutWithLabel = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
    };

    const { getFieldDecorator } = this.props.form;
    const meterForms = this.state.meterArr.map((item, index) => {
      return (
        <Form style={{ display: 'flex' }} className={`custom-table-form custom-table-form${index}`} key={index} layout="inline">
          <FormItem
            style={{ flex: '1', marginRight: '0' }}
          >
            {getFieldDecorator(`time-${item}`, {
            })(
              <TimePicker  format={'HH:mm'} style={{  fontWeight: 'bold' ,width:'235px'}}/>,
            )}
          </FormItem>
          <FormItem
            style={{ flex: '1', marginRight: '0' ,border:'1px solid #ccc'}}

          >
            {getFieldDecorator(`useMantissa-${item}`, {
              initialValue: false,
            })(
              <Switch style={{marginLeft:6}} checkedChildren="使用" unCheckedChildren="不使用" />
            )}
          </FormItem>
          <div style={{ width: '80px', lineHeight: '29px', textAlign: 'center', border: '1px solid #d9d9d9' }}>
            <div
              style={{ padding: '0 4px',color:'#fff',cursor:'pointer',background:'#dc0000' }}
              onClick={(e) => {
                e.stopPropagation();
                this.deleteMeter(item);
              }
              }
            >删除
            </div>
          </div>


        </Form>
      );
    });
    return (
      <div>
        <Form>
          <Form.Item style={{marginTop:'10px'}}  label="日上报类型"
                     {...formItemLayoutWithLabel}
          >
            {getFieldDecorator('type', {
              initialValue: (this.props.editRecord&&this.props.editRecord.hardware_configs.wh)?
                this.props.editRecord.hardware_configs.wh.upload_time.type:'',
              rules: [{required: true, message:'日上报类型不能为空'}],
            })(
              <Select  placeholder="请选择">
                {
                  [{type:0,name:'24小时随机（1天1次）'},{type:1,name:'自定义随机（1天1次）'},{type:2,name:'自定义（1天多次）'}].map((item,index)=>{
                    return <Option key={index} value={item.type}>
                      {item.name}
                    </Option>
                  })
                }
              </Select>,
            )}
          </Form.Item>
        </Form>
        <div style={{ border: '1px solid #d9d9d9', marginTop: '10px' }}>

          <div style={{
            display: 'flex',
            fontWeight: 'bold',
            lineHeight: '32px',
            height: '32px',
            background: 'rgb(249,249,249)',
          }}>
            <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>时间(时/分)</div>
            <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>使用设备号尾数</div>
            <div style={{ width: '80px', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>操作</div>

          </div>
          {meterForms}
          <Button type={'primary'} className={'btn-cyan'} icon={'plus'} block onClick={this.addMeter}>添加行</Button>

        </div>
        <Button type={'danger'} style={{ marginTop: '12px' }} icon={'table'} onClick={this.clearTable}>初始化表格</Button>
      </div>

    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);


